package com.gin.kotlin.gf2gamecommunity.base.composable

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.gin.kotlin.gf2gamecommunity.R
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.util.downloadManager
import com.gin.kotlin.gf2gamecommunity.base.util.enqueue

/**
 * 图片预览组件
 * @param urls 图片地址列表
 * @param dir 下载的图片保存的目录（英文）
 * @param initialIndex 初始位置，与初始url至少填写一个
 * @param initialUrl 初始url，与初始位置至少填写一个
 * @param modifier Modifier
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImagePreViewer(
    urls: List<String>,
    dir: String,
    initialIndex: Int? = null,
    initialUrl: String? = null,
    modifier: Modifier = Modifier
) {
    val initIndex = (initialIndex ?: initialUrl?.let { urls.indexOf(it) })?.takeIf { it >= 0 } ?: throw RuntimeException("初始位置和初始url至少需提供一个且不小于0")
    val pagerState = rememberPagerState(initialPage = initIndex, pageCount = { urls.size })

    // 手势缩放
    val downloadManager = LocalContext.current.downloadManager
    Scaffold(
        topBar = {
            TopAppBar(title = {
                Text("图片预览")
            }, actions = {
                IconButton(onClick = {
                    val url = urls[pagerState.currentPage]
                    downloadManager.enqueue(url = url, dir = dir)
                    App.toast("开始下载")
                }) {
                    Icon(painterResource(R.drawable.ic_download_24), contentDescription = "下载")
                }
            })
        }
    ) {
        HorizontalPagerWithIndicator(data = urls,
            indicatorConfig = IndicatorConfig().copy(range = 30.dp),
            pagerState = pagerState,
            modifier = modifier.padding(it)) { url ->
            TransformableImage(model = url, modifier = Modifier.fillMaxWidth())
        }
    }
}

